<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\market\MarketCollection;
use app\common\model\xiluhouse\market\MarketHouse;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\VillageBroker;
use think\Db;
use think\Exception;
use function fast\array_get;

/**
 * @title   租房类
 * @desc    获取租房房源、房源相关信息的接口
 */
class Market extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index', 'house_detail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';
    /**
     * @title  二手列表
     * @desc  获取-房源列表
     * @param string    $city             上海市                城市
     * @param string    $region           无                    区域
     * @param string    $street           无                    街道/镇
     * @param string    $keyword          无                    搜索关键词
     * @param string    $lat              31.235929042252       纬度
     * @param string    $lng              121.48053886018       经度
     * @param tinyint   $nearby           无                    附近几公里
     * @param int       $village_id         无                  小区id
     * @param int       $subway_id         无                   地铁线id
     * @param int       $subway_platform_id 无                  地铁站id
     * @param decimal   $min_price  0                           最小单价（万元）
     * @param decimal   $max_price  0                           最大单价（万元）（-1为无限大）
     * @param string    $search_roomnum_ids 无                   查询户型(多个id用英文逗号隔开)
     * @param string    $type_ids           无                   查询类型(多个id用英文逗号隔开)
     * @param string    $tag_ids            无                   查询标签(多个id用英文逗号隔开)
     */
    public function index(){
        $params = $this->request->param('');
        if($city = array_get($params,'city')){
            $map['village2.city'] = ['like', $city . '%'];
        }
        if($region = array_get($params,'region')){
            $map['village2.region'] = ['like', $region . '%'];
        }
        if ($street = array_get($params,'street')) {
            $map['village2.street'] = ['like', $street . '%'];
        }
        if($village_id = array_get($params,'village_id')) {
            $map['village_id'] = $village_id;
        }
        if($keyword = array_get($params,'keyword')) {
            $map['village2.name|village2.region'] = ['like', '%' . $keyword . '%'];
        }
        $map_text = [];
        //距离
        if ($nearby = array_get($params,'nearby')) {
            $lat = floatval($this->request->param('lat/s', '31.235929042252'));
            $lng = floatval($this->request->param('lng/s', '121.48053886018'));
            $map_text[] = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) <=' . $nearby;
        }
        //地铁
        if ($subway_id = array_get($params,'subway_id')) {
            $map_text[] = 'FIND_IN_SET(' . $subway_id . ',village2.subway_ids)';
        }
        //平台
        if ($subway_platform_id = array_get($params,'subway_platform_id')) {
            $map['village2.subway_platform_id'] = $subway_platform_id;
        }
        //单价
        $min_price = array_get($params,'min_price', 0);
        $max_price = array_get($params,'max_price', 0);
        if ($max_price > 0) {
            $map['price'] = ['BETWEEN', ($min_price) . ',' . ($max_price)];
        } else if ($max_price == -1) {
            $map['price'] = ['egt', $min_price];
        }
        //总价
        $min_total_price = array_get($params,'min_total_price', 0);
        $max_total_price = array_get($params,'max_total_price', 0);
        if ($max_total_price > 0) {
            $map['total_price'] = ['BETWEEN', ($min_total_price) . ',' . ($max_total_price)];
        } else if ($max_total_price == -1) {
            $map['total_price'] = ['egt', $min_total_price];
        }
        //居室
        $search_roomnum_ids = $this->request->param('search_roomnum_ids/s', '');
        if ($search_roomnum_ids) {
            $search_roomnum_data = \app\common\model\xiluhouse\market\SearchRoomnum::where('status', 'normal')->where('id', 'in', $search_roomnum_ids)->select();
            $roomnum_map_arr = [];
            foreach ($search_roomnum_data as $value) {
                if ($value['min_room_num'] == -1) {
                    $roomnum_map_arr[] = '(room_num >= ' . $value['min_room_num'] . ')';
                } else {
                    $roomnum_map_arr[] = '((room_num >= ' . $value['min_room_num'] . ' and room_num <= ' . $value['max_room_num'] . ') or (room_num >= ' . $value['min_room_num'] . ' and room_num <= ' . $value['max_room_num'] . '))';
                }
            }
            if (!empty($roomnum_map_arr)) {
                $map_text[] = implode(' or ', $roomnum_map_arr);
            }
        }
        $map_text = implode(" AND ",$map_text);

        //用途
        if($purpose_ids = array_get($params,'purpose_ids')){
            $map['purpose_id'] = ['in',$purpose_ids];
        }
        //装修
        if($decoration_ids = array_get($params,'decoration_ids')){
            $map['decoration_id'] = ['in',$decoration_ids];
        }
        $order = ['weigh' => 'desc', 'id' => 'desc'];
        $list = MarketHouse::with(['village2'=>function($query){
            $query->withField(['id','name','prov','city','region','street','addr','subway_ids','subway_platform_id']);
        }])
            ->where('market_house.status','normal')
            ->where('market_house.state','2')
            ->where($map)
            ->where($map_text)
            ->order($order)
            ->paginate()
            ->each(function ($row){
                $row->append(['image_text']);
            });
        $this->success('', $list);
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id   0   房源id
     */
    public function detail(){
        $id = $this->request->param('id/d', 0);
        $lat = floatval($this->request->param('lat/s', '31.235929042252'));
        $lng = floatval($this->request->param('lng/s', '121.48053886018'));
        $field = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) distance';
        $info = $id?MarketHouse::field("*,$field")->with(['purpose'=>function($query){
            $query->withField(['id','name']);
        },'decoration'=>function($query){
            $query->withField(['id','name']);
        },'village2'])->find($id) :null;
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['state'] != 2) {
            $this->error('该房源还在整改中');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        $info->distance = $info->distance < 1 ? sprintf("%.2f",$info->distance*1000).'m' : sprintf("%.2f",$info->distance).'km';
        //房源
        $info->append(['images_arr','image_text','room_images_text','video_file_text']);
        $info->village2->append(['nearby_bus_json_arr', 'nearby_subway_json_arr', 'nearby_school_json_arr', 'nearby_shop_json_arr', 'nearby_hospital_json_arr']);
        #当前小区经纪人
        if($info->is_public == 1){
            $broker_user_ids = VillageBroker::where('village_id',$info->village_id)->column('broker_user_id');
            $brokers = (new \app\common\model\xiluhouse\User)->field(['password','salt','verification','token','joinip','level','loginfailure','loginip','jointime','group_id','email','successions'],true)->with(['extension'])->whereIn("id",$broker_user_ids)->select();
        }else{
            $brokers = (new \app\common\model\xiluhouse\User)->field(['password','salt','verification','token','joinip','level','loginfailure','loginip','jointime','group_id','email','successions'],true)->with(['extension'])->where('id',$info['user_id'])->select();
        }
        $info['brokers'] = $brokers;
        // 给房源添加浏览量
        $info->setInc('view_num');
        $info['platform_contact_tel'] = \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel');

        //是否收藏
        $info['is_collection'] = $this->auth->isLogin() ? MarketCollection::where('market_id',$id)->where('user_id',$this->auth->id)->count('id') : 0;
        $this->success('', $info);
    }

    /**
     * 海报
     */
    public function poster(){
        $id = $this->request->param('id');
        $rentalQrcodeModel = new \app\common\model\xiluhouse\RentalQrcode;
        $exist = $rentalQrcodeModel->where('rental_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $data['share_qrcode_text'] = cdnurl($exist['url'],true);
        } else {
            $wxmini = new \app\common\library\xiluhouse\Wxmini;
            $res = $wxmini->getWXacode('user_' . $this->auth->id . ',rental_' . $id, 'pages/rental/renting/renting');
            if($res){
                $root = '.';
                $filename = md5(mt_rand()).'.png';
                $path = "/uploads/".date('Ymd').'/';
                if (!file_exists($root . $path)) {
                    @mkdir($root . $path, 0777, true);
                }
                $qrcode = $path.$filename;
                if(!get_addon_config('alioss')){
                    file_put_contents($root.$qrcode,$res);
                }else{
                    Common::uploadAlioss($qrcode, $res);
                }
                if ($qrcode) {
                    $rentalQrcodeModel->insert(['rental_id' => $id, 'user_id' => $this->auth->id, 'url' => $qrcode]);
                }
                if(!$qrcode){
                    $qrcode = \app\common\model\xiluhouse\Config::getdatas('wxmini_logo');
                }
                $data['share_qrcode_text'] = cdnurl($qrcode,true);
            }
        }
    }

    /**
     * 推荐房源
     */
    public function recommend_market(){
        $id = $this->request->param('id');
        $villageId = $id ? MarketHouse::where('id',$id)->value('village_id'):0;
        if(!$villageId){
            $this->error("未找到房源");
        }
        $village = Village::where('id',$villageId)->find();
        if(!$village){
            $this->success("",[]);
        }
        // 获取推荐房源
        $recommendLists = MarketHouse::with([
            'village2'=>function($query){
            $query->withField(['id','name','prov','city','region','street','addr','subway_ids','subway_platform_id']);
        }])
            ->where('market_house.id', 'neq', $id)
            ->where('market_house.status', 'normal')
            ->where('market_house.state', 2)
            ->where('prov', $village['prov'])
            ->where('city', $village['city'])
            ->orderRaw('rand()')
            ->limit(5)
            ->select();
        foreach ($recommendLists as $recommendList) {
            $recommendList->append(['image_text']);
        }
        unset($recommendList);
        $this->success('',$recommendLists);
    }

    /**
     * @ApiTitile (收藏&取消收藏)
     * @ApiSummary (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluehouse.market/toggle_collection)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=rental_id, type=int, require=true, description="id")
     */
    public function toggle_collection() {
        $market_id = $this->request->post('market_id');
        $user_id = $this->auth->id;
        Db::startTrans();
        try {
            $model = MarketCollection::where('user_id', $user_id)
                ->where('market_id', $market_id)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new MarketCollection([
                    'user_id' => $user_id,
                    'market_id' => $market_id
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    throw new Exception($model->getError());
                }
                $result = true;
            }
            $collectionCount = MarketCollection::where('market_id', $market_id)->count();
            MarketHouse::where('id', $market_id)->update(['collection_num' => $collectionCount]);
        }catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('操作成功',['is_collection'=>$result?1:0]);
    }

}
